﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Caching.Memory;
using KongMing.Project.Entity.Common;
using Microsoft.AspNetCore.Authentication;
using KongMing.Project.Common;

namespace KongMing.Project.Service
{
    public abstract class BaseService
    {
        #region 通用的属性

        //每次请求的JwtToken中的用户信息
        public ApiUserContext ApiUserContext { get; private set; } = new ApiUserContext();

        public IServiceProvider ServiceProvider { get; private set; }

        public IHttpContextAccessor HttpContextAccessor { get; private set; }
        /// <summary>
        /// HttpContext上下文
        /// </summary>
        public HttpContext HttpContext { get; private set; }
        /// <summary>
        /// 配置文件
        /// </summary>
        public IConfiguration Configuration { get; private set; }
        /// <summary>
        /// 缓存
        /// </summary>
        public IMemoryCache MCache { get; set; }
        /// <summary>
        /// 业务库
        /// </summary>
        public BusinessDBContext BusinessDB { get; set; }
        /// <summary>
        /// 主库
        /// </summary>
        public MainDBContext MainDB { get; set; }

        #endregion
        public BaseService(IServiceProvider serviceProvider)
        {
            ServiceProvider = serviceProvider;
            HttpContextAccessor = ServiceProvider.GetService<IHttpContextAccessor>();
            HttpContext = HttpContextAccessor.HttpContext;
            Configuration = ServiceProvider.GetService<IConfiguration>();
            MCache = ServiceProvider.GetService<IMemoryCache>();
            BusinessDB = ServiceProvider.GetService<BusinessDBContext>();
            MainDB = ServiceProvider.GetService<MainDBContext>();
            GetApiRequestData();
        }

        protected T GetService<T>() => ServiceProvider.GetService<T>();

        /// <summary>
        /// 获取每次请求的用户身份信息
        /// </summary>
        private void GetApiRequestData()
        {
            var path = HttpContext.Request.Path;

            string baseRequestUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}{HttpContext.Request.Path}{HttpContext.Request.QueryString}";
            ApiUserContext.FullUrl = new Uri(baseRequestUrl);
            ApiUserContext.OriginUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}";

            //获取请求中的Jwt配置
            string bearer = HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (string.IsNullOrEmpty(bearer) || !bearer.Contains("Bearer"))
                return;
            try
            {
                string token = bearer.Split(' ')[1];
                string token_2 = HttpContext.GetTokenAsync("Bearer", "access_token").Result;
                var tokenObj = new JwtSecurityToken(token) ?? new JwtSecurityToken();
                var claimsIdentity = new ClaimsIdentity(tokenObj.Claims) ?? new ClaimsIdentity();
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity) ?? new ClaimsPrincipal();
                HttpContext.User = claimsPrincipal;

                ApiUserContext.UserName = claimsPrincipal?.Claims?.Where(x => x.Type == ClaimTypes.Name).FirstOrDefault()?.Value;
                ApiUserContext.UserAccount = claimsPrincipal?.Claims?.Where(x => x.Type == "Account").FirstOrDefault()?.Value;
                ApiUserContext.UserId = claimsPrincipal?.Claims?.Where(x => x.Type == "UserId").FirstOrDefault()?.Value;
                ApiUserContext.JwtToken = token;
            }
            catch (Exception ex)
            {

            }
        }
    }
}
